package com.igelato.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.igelato.mapper.CouponMapper;
import com.igelato.model.Coupon;
import com.igelato.model.User;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.igelato.mapper.UserMapper;
import com.igelato.utils.JwtToken;
import com.igelato.utils.ThreadLocalTool;
import com.igelato.utils.Tools;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;

/**
 * @TableName: user
 * @Description:
 * @Author: wht
 * @Date: 2024-01-24
 */

@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    UserMapper userMapper;

    @Autowired
    CouponMapper couponMapper;

    public User login(String openid) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);
        User user = userMapper.selectOne(queryWrapper);

        if (user == null) {
//        没有user，则创建user -------------------
            user = new User();
            user.setOpenid(openid);
            userMapper.insert(user);
        } else {
//        优惠券 -------------------
            addCouponListToUser(user);
        }

//        设置token -------------------
        String token = JwtToken.getToken(user.getId());
        ThreadLocalTool.setToken(token);

        return user;
    }

    public User getOneUserById(Integer user_id) {
        User user = userMapper.selectById(user_id);

//        优惠券 -------------------
        addCouponListToUser(user);

        return user;
    }

    public String savePhoneNumber(String code) {
//        用code换手机号-------------------
        String url = "http://api.weixin.qq.com/wxa/business/getuserphonenumber";
        HashMap<String, String> body = new HashMap<>();
        body.put("code", code);
        JSONObject res = JSON.parseObject(Tools.httpPost(url, body));
        String mobile = (String) ((JSONObject) res.get("phone_info")).get("phoneNumber");

        //  存数据-----------------------
        Integer user_id = ThreadLocalTool.getUserId();
        User user = new User();
        user.setId(user_id);
        user.setMobile(mobile);
        Integer res_user = userMapper.updateById(user);
        if (res_user != 1) {
            throw new RuntimeException("更新用户手机号失败");
        }

//        更新redis里的数据 -------------------
        User user_redis = getUser();
        user_redis.setMobile(mobile);
        setUserRedis(user_redis);

        return mobile;
    }


    public void addCouponListToUser(User user) {
        LambdaQueryWrapper<Coupon> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Coupon::getUser_id, user.getId());
        List<Coupon> couponList = couponMapper.selectList(queryWrapper1);
        user.setCouponList(couponList);
    }


    //    redis ----------------------------------------------
    final private static String REDIS_KEY_USER = "USER_";
    public User getUser() {
        Integer user_id = ThreadLocalTool.getUserId();
        User user = (User) redisTemplate.opsForValue().get(REDIS_KEY_USER + user_id);
        if (user == null) {
//            reids里没有user，则从数据库里取-------------------
            user = getOneUserById(user_id);
            setUserRedis(user);
        }
        return user;
    }

    public void setUserRedis(User user) {
        if (user == null) return;
        redisTemplate.opsForValue().set(REDIS_KEY_USER + user.getId(), user);
    }

}
